const cloud = require('wx-server-sdk')
cloud.init({
    env: process.env.ENV_ID
})

exports.main = async (event, context) => {
    const { keywords, page = 1, pageSize = 10 } = event
    const db = cloud.database()
    const _ = db.command

    const query = {}
    if (keywords) {
        // 分割关键词为多个标签
        const tags = keywords.split(/[,，\s]+/).filter(tag => tag.trim())

        // 特殊标签处理（如'橙色风格'等）
        const specialTags = ['橙色风格', '灰色风格', '表格简历']
        const hasSpecialTag = tags.some(tag => specialTags.includes(tag))

        if (hasSpecialTag) {
            // 精确匹配特殊标签
            query.tags = _.in(tags)
        } else {
            // 普通关键词搜索
            query.$or = [
                { title: db.RegExp({ regexp: keywords, options: 'i' }) },
                { description: db.RegExp({ regexp: keywords, options: 'i' }) },
                { tags: _.in(tags) }
            ]
        }
    }

    const { data } = await db.collection('resume_templates')
        .where(query)
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .get()

    return {
        success: true,
        data,
        page,
        pageSize
    }
}